<template>
  <div class="layer-monitor">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>{{ layer }}层监控</span>
          <el-button type="primary" size="small" @click="$router.push('/monitor/tables')">查看所有表</el-button>
        </div>
      </template>
      
      <div v-if="layerData" class="layer-overview">
        <!-- 层概览统计 -->
        <el-row :gutter="20">
          <el-col :span="6">
            <el-statistic title="表数量" :value="layerData.table_count" />
          </el-col>
          <el-col :span="6">
            <el-statistic title="总行数" :value="formatNumber(layerData.total_rows)" />
          </el-col>
          <el-col :span="6">
            <el-statistic title="数据大小" :value="formatDataSize(layerData.total_size)" />
          </el-col>
          <el-col :span="6">
            <el-statistic title="健康状态">
              <template #value>
                <el-tag :type="getHealthType(layerData.health_status)">
                  {{ getHealthText(layerData.health_status) }}
                </el-tag>
              </template>
            </el-statistic>
          </el-col>
        </el-row>

        <!-- 该层下的表列表 -->
        <el-card title="表列表" style="margin-top: 20px;">
          <el-table :data="layerTables" style="width: 100%" v-loading="tablesLoading">
            <el-table-column prop="table_name" label="表名" />
            <el-table-column prop="database_name" label="数据库" />
            <el-table-column prop="description" label="描述" show-overflow-tooltip />
            <el-table-column prop="is_active" label="状态" width="100">
              <template #default="{ row }">
                <el-tag :type="row.is_active ? 'success' : 'danger'" size="small">
                  {{ row.is_active ? '启用' : '禁用' }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column label="操作" width="150">
              <template #default="{ row }">
                <el-button type="text" size="small" @click="viewTableDetail(row)">
                  查看详情
                </el-button>
                <el-button type="text" size="small" @click="viewTableData(row)">
                  查看数据
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-card>

        <!-- 层数据趋势图 -->
        <el-card title="数据趋势" style="margin-top: 20px;">
          <div class="chart-container">
            <v-chart :option="chartOption" style="height: 400px;" />
          </div>
        </el-card>
      </div>

      <div v-else class="loading-container">
        <el-skeleton :rows="10" animated />
      </div>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, computed } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { use } from 'echarts/core'
import { CanvasRenderer } from 'echarts/renderers'
import { LineChart } from 'echarts/charts'
import { GridComponent, TooltipComponent, LegendComponent } from 'echarts/components'
import VChart from 'vue-echarts'
import { monitorApi } from '@/api/monitor'
import type { LayerOverview, MonitoredTable } from '@/types'

// 注册 ECharts 组件
use([CanvasRenderer, LineChart, GridComponent, TooltipComponent, LegendComponent])

const route = useRoute()
const router = useRouter()
const layer = ref(route.params.layer as string)
const layerData = ref<LayerOverview | null>(null)
const layerTables = ref<MonitoredTable[]>([])
const tablesLoading = ref(false)

const loadLayerData = async () => {
  try {
    const response = await monitorApi.getLayerDetail(layer.value)
    layerData.value = response.data
  } catch (error) {
    console.error('Failed to load layer data:', error)
    ElMessage.error('加载层数据失败')
  }
}

const loadLayerTables = async () => {
  tablesLoading.value = true
  try {
    const response = await monitorApi.getTables({ layer: layer.value })
    layerTables.value = response.data.items
  } catch (error) {
    console.error('Failed to load layer tables:', error)
    ElMessage.error('加载表列表失败')
  } finally {
    tablesLoading.value = false
  }
}

const viewTableDetail = (table: MonitoredTable) => {
  router.push(`/monitor/table/${table.id}`)
}

const viewTableData = (table: MonitoredTable) => {
  // 这里可以跳转到数据预览页面，或者打开数据预览对话框
  ElMessage.info(`查看表 ${table.table_name} 的数据`)
}

const formatNumber = (num: number): string => {
  if (num >= 1000000) {
    return (num / 1000000).toFixed(2) + 'M'
  } else if (num >= 1000) {
    return (num / 1000).toFixed(2) + 'K'
  }
  return num.toString()
}

const formatDataSize = (bytes: number): string => {
  if (bytes === 0) return '0 B'
  const k = 1024
  const sizes = ['B', 'KB', 'MB', 'GB', 'TB']
  const i = Math.floor(Math.log(bytes) / Math.log(k))
  return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i]
}

const getHealthType = (status: string): string => {
  const types: Record<string, string> = {
    'healthy': 'success',
    'warning': 'warning',
    'error': 'danger'
  }
  return types[status] || 'info'
}

const getHealthText = (status: string): string => {
  const texts: Record<string, string> = {
    'healthy': '健康',
    'warning': '警告',
    'error': '错误'
  }
  return texts[status] || status
}

// 图表配置
const chartOption = computed(() => ({
  title: {
    text: `${layer.value}层数据趋势`,
    left: 'center'
  },
  tooltip: {
    trigger: 'axis'
  },
  legend: {
    data: ['表数量', '总行数', '数据大小'],
    top: 30
  },
  grid: {
    left: '3%',
    right: '4%',
    bottom: '3%',
    containLabel: true
  },
  xAxis: {
    type: 'category',
    data: ['1月', '2月', '3月', '4月', '5月', '6月']
  },
  yAxis: [
    {
      type: 'value',
      name: '数量',
      position: 'left'
    },
    {
      type: 'value',
      name: '大小(MB)',
      position: 'right'
    }
  ],
  series: [
    {
      name: '表数量',
      type: 'line',
      data: [10, 15, 18, 22, 25, 28]
    },
    {
      name: '总行数',
      type: 'line',
      yAxisIndex: 1,
      data: [1000000, 1500000, 1800000, 2200000, 2500000, 2800000]
    }
  ]
}))

onMounted(() => {
  loadLayerData()
  loadLayerTables()
})
</script>

<style scoped>
.layer-monitor {
  padding: 0;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.layer-overview {
  margin-top: 20px;
}

.chart-container {
  margin: 20px 0;
}

.loading-container {
  margin-top: 20px;
}
</style> 